package org.jeecg.modules.sys_captcha.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import org.jeecg.modules.sys_captcha.entity.SysCaptcha;
import org.jeecg.modules.sys_captcha.mapper.SysCaptchaMapper;
import org.jeecg.modules.sys_captcha.service.ISysCaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.util.Calendar;
import java.util.Date;

@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptcha> implements ISysCaptchaService {

    @Autowired
    private Producer producer;
    @Autowired
    private SysCaptchaMapper captchaMapper;

    @Override
    public BufferedImage generateCaptcha(String uuid) {
        // 生成文字验证码
        String code = producer.createText();

        SysCaptcha captcha = new SysCaptcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        // 5分钟过期
        captcha.setExpireTime(calendar.getTime());
        this.save(captcha);

        // 生成图片验证码
        return producer.createImage(code);
    }

    @Override
    @Transactional
    public boolean validate(String uuid, String code) {
        SysCaptcha captcha = captchaMapper.selectOne(new QueryWrapper<SysCaptcha>().eq("uuid", uuid));

        if(captcha == null) {
            return false;
        }

        // 删除验证码
        captchaMapper.deleteById(captcha);

        // 验证验证码
        if(captcha.getCode().equalsIgnoreCase(code) &&
                captcha.getExpireTime().after(new Date())) {
            return true;
        }

        return false;
    }

    @Override
    public void clearExpiredCaptchas(Date now) {
        // 删除过期验证码
        captchaMapper.deleteExpiredCaptchas(now);
    }
}
